import 'dart:math';

import 'package:flutter/material.dart';

import 'trapezoid_widget.dart';

// 定义一个类型别名来表示构建函数

class DiagonalGridView extends StatelessWidget {
  const DiagonalGridView(
      {super.key,
      required this.itemCount,
      required this.slope,
      this.placeHolder,
      required this.childAspectRatio,
      required this.itemBuilder});

  final int itemCount;

  final double slope;

  final double childAspectRatio;

  final Widget? placeHolder;

  final NullableIndexedWidgetBuilder itemBuilder;

  List<Container> createRowList(
      List<Widget> items, int itemsPerRow, Size size) {
    List<Container> rows = [];
    for (int i = 0; i < items.length; i += itemsPerRow) {
      int startIndex = i;
      int endIndex = i + itemsPerRow; // 这个索引超出了列表的范围
      List<Widget> rowItems = [];
      if (startIndex >= 0 &&
          endIndex <= items.length &&
          startIndex <= endIndex) {
        rowItems = items.sublist(startIndex, endIndex);
      } else {
        rowItems = [items[i]];
      }

      rows.add(Container(
          width: size.width,
          height: size.height,
          child: Stack(children: rowItems)));
    }
    return rows;
  }

  int calulateRows(int n) {
    int rows = n ~/ 2;
    if (n % 2 != 0) {
      rows += 1;
    }
    return max(rows, 1);
  }

  @override
  Widget build(BuildContext context) {
    // 一行两列
    // var rows = calulateRows(itemCount) * 1.0;

    return LayoutBuilder(builder: (context, constraints) {
      // 这里你可以访问constraints.maxWidth和constraints.maxHeight
      // 但这些只是父级widget提供的约束，不是实际的宽高

      var _slope = slope;
      var other = (1 - _slope);

      // var offSet = (_slope - other).abs();
      double topWidth = _slope * constraints.maxWidth;
      double bottomWidth = other * constraints.maxWidth;

      double maxWidth = max(topWidth, bottomWidth);
      double childHeight = maxWidth * childAspectRatio;

      List<Widget> itemWidgets = List.generate(itemCount, (index) {
        var isOddNumbers = index % 2 == 1;
        // var curRow = calulateRows(index);

        double _topWidth = _slope * constraints.maxWidth;
        double _bottomWidth = (1 - _slope) * constraints.maxWidth;
// 小于 0.5, top 大 -》 小
//         print("[item] $curRow/$rows slope:$slope _off:$_off _slope:$_slope top:$_topWidth $_bottomWidth");

        return Positioned(
            left: isOddNumbers ? null : 0,
            right: isOddNumbers ? 0 : null,
            child: TrapezoidWidget(
                child: itemBuilder(context, index) ??
                    Center(child: Icon(Icons.error)),
                color: isOddNumbers ? Colors.blue : Colors.green,
                topWidth: _topWidth,
                bottomWidth: _bottomWidth,
                height: childHeight,
                flip: isOddNumbers));
      });
      var children = createRowList(
          itemWidgets, 2, Size(constraints.maxWidth, childHeight));

      return Column(children: children);
    });
  }
}
